<script setup>
import { computed, onMounted, reactive, ref, watchEffect } from 'vue';
import data from "@/untils/address/states.json"
const formLabelWidth = '200px'
//  import dayjs from "dayjs"
import { ElMessage } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import IconSelect from '@/components/IconSelect/index.vue'
import { getMenuList, addMenuapi, EditMenuapi, delMenuapi } from '../../api/api';
let formRef = ref(null)
let props = defineProps({
    dialogFormVisible: Boolean,
    formlist: Object,
    changeType: String,
    tableData: Array,
})
const datasel = ref([]);
const states = ref([]);
const countryStates = ref({});
let menulist = ref([{
    "menuId": 0,
}])
watchEffect(() => {
    console.log(props.dialogFormVisible);
    if (props.dialogFormVisible) {
        getMenuList().then(res => {
            console.log(res, "router/菜单数据");
            const originalMenuData = res.data
            const rootMenu = {
                menuId: 0,
                menuName: "Top menu",
                children: originalMenuData
            };
            menulist.value = [rootMenu];
            console.log(menulist.value);

        })

    }
})
onMounted(async () => {
    // if (props.dialogFormVisible) {
    //     console.log("6666");

    // }
    // console.log("111");

    // let res = await getMenuList()
    // console.log(res, "router/菜单数据");

    // // 原始菜单数据
    // const originalMenuData = props.tableData;

    // // 添加顶级菜单（menuId=0 表示顶级）
    // const rootMenu = {
    //     menuId: 0,
    //     menuName: "Top menu",
    //     children: originalMenuData  // 将原有菜单作为子节点
    // };

    // // 更新 menulist
    // menulist.value = [rootMenu];  // 注意这里要包装成数组

    // console.log("data", data.data);
    // datasel.value = data.data;
    // // 将数据转换为{国家名: [州数组]}的格式
    // const tempCountryStates = {};
    // data.data.forEach(country => {
    //     tempCountryStates[country.name] = country.states || [];
    // });
    // console.log(props.formlist.contry, "国家");
    // console.log(props.formlist.addresszhou, "州");

})
// let form = reactive({
//     parentId: "",
//     menuType: 1,
//     menuName: "",
//     icon: "",
//     orderNum: 0
// })
const selected = (name) => {
    form.icon = name
}
// 自定义下拉菜单展开状态
const dropdownVisible = ref(false)
// 当前选中的菜单项
const selectedMenuItem = ref(null)
// 当前展开的子菜单项
const expandedSubmenu = ref(null)

// 处理菜单选择
const handleMenuSelect = (item) => {
    selectedMenuItem.value = item
    form.parentId = item.menuId
    dropdownVisible.value = false // 选择后关闭下拉框
}
// 切换子菜单展开状态
const toggleSubmenu = (item) => {
    if (expandedSubmenu.value === item.menuId) {
        expandedSubmenu.value = null // 如果已经展开，则收起
    } else {
        expandedSubmenu.value = item.menuId // 否则展开
    }
}
// let form = reactive({
//     className: '',
//     classroom: '',
//     ht: '',
//     startDate: '',
// let topdata = ref(props.topdata)
//    let topdata = ref({
//         school:"",
//         username:"",
//         tel:"",
//         person:"",
//         time:"",
//         pwd:"",
//         flag:1
//     })

// let editForm = computed(()=>{
//     return {

//     };
// })
// const form = reactive({
//     className: '',
//     classroom: '',
//     ht: '',
//     startDate: '',
//     classStatus:0,
// })

let emits = defineEmits(["close", 'update:formlist'])
function closedialog(formEl) {
    // // 再次点击清空inp的值
    if (!formEl) return
    formEl.resetFields()
    // // // 向父组件发送自定义事件
    emits("close")
}
async function addsubmit(formEl) {

    if (props.formlist.menuType == 1) {
        if (props.formlist.menuName == "" || props.formlist.path == "" || props.formlist.component == "") {
            ElMessage.warning("Please fill in the required fields");
            return;
        }
    } else if (props.formlist.menuType == 2) {
        if (props.formlist.perms == "") {
            ElMessage.warning("Please fill in the required fields");
            return;
        }
    }

    if (props.changeType == "add") {
        // 添加操作
        console.log(props.formlist, "新增数据");
        if (props.formlist.menuType == 1) {
            console.log(props.formlist.parentId); //上级菜单
            console.log(props.formlist.menuType);//菜单类型
            console.log(props.formlist.menuName);//菜单名称
            console.log(props.formlist.icon);//图标
            console.log(props.formlist.orderNum);//排序
            console.log(props.formlist.path);//路由地址
            console.log(props.formlist.component);//组件路径
            try {
                let res = await addMenuapi(props.formlist.menuName, "", props.formlist.icon, props.formlist.parentId, props.formlist.orderNum, props.formlist.path, props.formlist.component, props.formlist.menuType)
                console.log(res);
                if (res.code == 200) {
                    ElMessage({
                        message: 'Added successfully',
                        type: 'success',
                    })
                }
            } catch (error) {
                console.log(error);

            }
        } else if (props.formlist.menuType == 2) {
            console.log(props.formlist.parentId); //上级菜单
            console.log(props.formlist.menuType);//菜单类型
            console.log(props.formlist.menuName);//菜单名称
            console.log(props.formlist.perms);//权限标识
            console.log(props.formlist.orderNum);//排序
            try {
                let res = await addMenuapi(props.formlist.menuName, props.formlist.perms, "", props.formlist.parentId, props.formlist.orderNum, "", "", props.formlist.menuType)
                if (res.code == 200) {
                    ElMessage({
                        message: 'Added successfully',
                        type: 'success',
                    })
                }
            } catch (error) {
                console.log(error);
            }
        }
        emits("close")
    } else if (props.changeType == "update") {
        // //编辑操作
        console.log(props.formlist, "编辑数据");
        if (props.formlist.menuType == 1) {
            console.log(props.formlist.parentId); //上级菜单
            console.log(props.formlist.menuType);//菜单类型
            console.log(props.formlist.menuName);//菜单名称
            console.log(props.formlist.icon);//图标
            console.log(props.formlist.orderNum);//排序
            console.log(props.formlist.path);//路由地址
            console.log(props.formlist.component);//组件路径
            try {
                let res = await EditMenuapi(props.formlist.menuId, props.formlist.menuName, "", props.formlist.icon, props.formlist.parentId, props.formlist.orderNum, props.formlist.path, props.formlist.component, props.formlist.menuType)
                console.log(res);
                if (res.code == 200) {
                    ElMessage({
                        message: 'Edited successfully',
                        type: 'success',
                    })
                }
            } catch (error) {
                console.log(error);
            }
        } else if (props.formlist.menuType == 2) {
            console.log(props.formlist.parentId); //上级菜单
            console.log(props.formlist.menuType);//菜单类型
            console.log(props.formlist.menuName);//菜单名称
            console.log(props.formlist.perms);//权限标识
            console.log(props.formlist.orderNum);//排序
            try {
                let res = await EditMenuapi(props.formlist.menuId, props.formlist.menuName, props.formlist.perms, "", props.formlist.parentId, props.formlist.orderNum, "", "", props.formlist.menuType)
                if (res.code == 200) {
                    ElMessage({
                        message: 'Edited successfully',

                        type: 'success',
                    })
                }
            } catch (error) {
                console.log(error);
            }
        }
        emits("close")

        // let {data} = await updateschoolbasics(props.formlist)
        // if(data.code == 200){
        //     if(data.data.affectedRows > 0){
        //         ElMessage({
        //             message: '修改成功！',
        //             type: 'success',
        //         })
        //         closedialog(formEl)
        //     }
        // }
    }
}
// function handleChangeuserLevel(e){
//     console.log(e);
// }
// // 重置表单
// const resetForm = () => {
//     form.menuId = undefined
//     form.menuName = ''
//     form.parentId = 0
//     form.menuType = 'M'
//     form.path = ''
//     form.component = ''
//     form.perms = ''
//     form.icon = ''
//     form.orderNum = 0
//     form.visible = 0
//     form.isFrame = '0'
//     if (formRef.value) {
//         formRef.value.resetFields()
//     }
// }

// 取消按钮
const cancel = () => {
    open.value = false
    resetForm()
}


// 加载菜单树
const getMenuTree = () => {
    listMenu().then(response => {
        menuOptions.value = response.data
    })
}

// 树形选择器转换
const normalizer = node => {
    if (node.children && !node.children.length) {
        delete node.children
    }
    return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
    }
}
const iconSearch = ref('')
const icons = [
    'user', 'Minus', "CirclePlus", "Loading", "Setting", "House", "UserFilled", "Avatar", "CircleCheck", "Setting", "Document", "Notification", "Setting", "PriceTag", "SetUp", "DataAnalysis", "Reading", "FolderOpened", "DocumentChecked", "ScaleToOriginal", "DocumentDelete"
]
// 计算属性，过滤图标
const filteredIcons = computed(() => {
    if (!iconSearch.value) return icons
    return icons.filter(icon =>
        icon.toLowerCase().includes(iconSearch.value.toLowerCase())
    )
})
// 处理图标选择
const handleIconSelect = (icon) => {
    props.formlist.icon = icon
    //   iconSearch.value = '' // 清空搜索框
}

// 监听form.icon变化，当外部修改时更新选中状态
watchEffect(() => {
    if (props.formlist.icon && !filteredIcons.value.includes(props.formlist.icon)) {
        // 如果当前图标不在列表中，可以添加到列表或做其他处理
        console.warn(`Icon ${props.formlist.icon} not found in the icon list`)
    }
})
let icondiv = ref(false)
const rulesMenu = {
    menuName: [
        { required: true, message: 'The menu name cannot be empty', trigger: 'blur' }
    ],
    // parentId: [
    //     { required: true, message: 'The superior menu cannot be empty', trigger: 'change' }
    // ],
    // menuType: [
    //     { required: true, message: 'Menu type cannot be empty', trigger: 'change' }
    // ],
    perms: [
        { required: true, message: 'Permission identifier cannot be empty', trigger: 'change' }
    ],
    // 如果 path 在非按钮类型时必填
    path: [
        {
            required: true,
            message: 'The routing address cannot be empty',
            trigger: 'blur',
            validator: (rule, value, callback) => {
                if (props.formlist.menuType !== 2 && !value) {
                    callback(new Error('The routing address cannot be empty'));
                } else {
                    callback();
                }
            }
        }
    ],
    // 如果 component 在非按钮类型时必填
    component: [
        {
            required: true,
            message: 'Component address cannot be empty',
            trigger: 'blur',
            validator: (rule, value, callback) => {
                if (props.formlist.menuType !== 2 && !value) {
                    callback(new Error('Component address cannot be empty'));
                } else {
                    callback();
                }
            }
        }
    ]
}
</script>
<template>
    <div class="editclass">
        <el-dialog :model-value="dialogFormVisible" style="padding: 20px;width: 580px;"
            :title="changeType == 'add' ? 'add' : 'edit'" @close="closedialog(formRef)">
            <el-form :model="formlist" ref="formRef" class="two-column-form" :rules="rulesMenu">
                <!-- 上级菜单 -->
                <!-- 自定义上级菜单下拉框 -->
                <el-form-item label="previous menu" :label-width="formLabelWidth" prop="parentId">
                    <el-tree-select v-model="formlist.parentId" :data="menulist" :props="{
                        value: 'menuId',  // 指定节点的value字段
                        label: 'menuName', // 指定节点的label字段
                        children: 'children' // 指定子节点字段
                    }" node-key="menuId" :expand-on-click-node="false" :check-strictly="true" style="width: 240px" />
                </el-form-item>
                <el-form-item label="menu type" prop="menuType" style="margin-left: 60px;">
                    <el-radio-group v-model="formlist.menuType">
                        <el-radio :value="1">menu</el-radio>
                        <el-radio :value="2">button</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="menu name" :label-width="formLabelWidth" prop="menuName">
                    <el-input v-model="formlist.menuName" autocomplete="off" placeholder="Please enter the menu name"
                        style="width: 200px;" maxlength="30" />
                </el-form-item>
                <el-form-item label="Permission identification" :label-width="formLabelWidth" prop="perms"
                    v-if="formlist.menuType == 2">
                    <el-input v-model="formlist.perms" autocomplete="off"
                        placeholder="Please enter the permission identifier" style="width: 200px;" maxlength="30" />
                </el-form-item>
                <el-form-item label="icon" :label-width="formLabelWidth" prop="icon" @click.stop
                    v-if="formlist.menuType !== 2">
                    <!-- <el-input v-model="form.icon" autocomplete="off" placeholder="请输入图标名称" style="width: 200px;"
                        @click.stop="() => icondiv = true" @blur="() => icondiv = false" /> -->
                    <!-- <div class="icon-selector" v-show="icondiv"> -->
                    <!-- 搜索框 -->
                    <!-- <div class="search-container">
                            <input type="text" placeholder="请输入图标名称" class="search-input" v-model="iconSearch"
                                @click.stop>
                            <button class="search-button">
                                <i class="search-icon">🔍</i>
                            </button>
                        </div> -->
                    <el-popover placement="bottom" :width="600" trigger="click">
                        <div class="icons-grid"
                            style="height: 240px;overflow: scroll;padding: 20px;overflow-x: hidden;">
                            <div class="icon-item" v-for="item in icons" :key="item" @click="handleIconSelect(item)"
                                style="cursor: pointer;">
                                <el-icon>
                                    <component :is="item" />
                                </el-icon>
                                <span class="icon-text">{{ item }}</span>
                            </div>
                        </div>
                        <template #reference>
                            <el-input class="m-2" style="width: 200px;" placeholder="Please select an icon "
                                v-model="formlist.icon" maxlength="30"></el-input>
                        </template>
                    </el-popover>
                </el-form-item>
                <!-- 显示顺序 -->
                <el-form-item label="order" :label-width="formLabelWidth" prop="orderNum">
                    <el-input-number v-model="formlist.orderNum" :min="0" :max="30" />
                </el-form-item>
                <!-- 路由地址 -->
                <el-form-item label="Routing address" :label-width="formLabelWidth" prop="path"
                    v-if="formlist.menuType !== 2">
                    <el-input v-model="formlist.path" autocomplete="off" placeholder="Please enter the routing address"
                        style="width: 200px;" maxlength="30" />
                </el-form-item>
                <!-- 组件地址 -->
                <el-form-item label="Component Address" :label-width="formLabelWidth" prop="component"
                    v-if="formlist.menuType !== 2">
                    <el-input v-model="formlist.component" autocomplete="off"
                        placeholder="Please enter the component address" style="width: 200px;" maxlength="30" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closedialog(formRef)">cancel</el-button>
                    <el-button type="primary" @click="addsubmit(formRef)">
                        {{ changeType == "add" ? 'add' : 'edit' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>
<!-- <style lang="scss" scoped>
.two-column-form .form-row {
    display: flex;
    justify-content: space-between;
}

.two-column-form .el-form-item {
    width: 48%;
}
</style> -->
<style lang="scss" scoped>
.two-column-form .form-row {
    display: flex;
    justify-content: space-between;
}

// .two-column-form .el-form-item {
//     // width: 48%;
// }

.address-container {
    display: flex;
    align-items: center;
}

/* 调整表单标签宽度 */
.two-column-form :deep(.el-form-item__label) {
    // width: 80px;
    text-align: right;
    padding-right: 12px;
}

/* 自定义下拉菜单样式 */
.custom-select {
    position: relative;
    width: 100%;

    .select-input {
        width: 180%;

        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 10px;
        height: 36px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        cursor: pointer;

        .el-icon {
            margin-left: 5px;
        }
    }

    .dropdown-menu {
        position: absolute;
        top: 100%;
        left: 0;
        // width: 190%;
        background-color: #fff;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        z-index: 1000;
        max-height: 300px;
        overflow-y: auto;

        .menu-item {
            padding: 8px 15px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;

            &:hover {
                background-color: #f5f7fa;
            }

            &.is-selected {
                font-weight: bold;
            }

            .expand-icon {
                margin-left: 5px;
                transition: transform 0.3s;
            }
        }

        .submenu {
            padding-left: 20px;

            .submenu-item {
                padding: 6px 15px;
                cursor: pointer;

                &:hover {
                    background-color: #f5f7fa;
                }
            }
        }
    }
}

/* 响应式设计 - 小屏幕时变为单列 */
@media (max-width: 768px) {
    .two-column-form .form-row {
        flex-direction: column;

        .el-form-item {
            width: 100%;
        }
    }

    .address-container {
        flex-direction: column;
        align-items: flex-start;

        .el-select {
            width: 100% !important;
            margin-right: 0 !important;
            margin-bottom: 10px;
        }
    }
}

.menu-icon {
    width: 25px;
    height: 25px;
}

// .icon-selector {
//     width: 100%;
//     height: 200px;
//     overflow: scroll;
//     background-color: #fff;
//     border: 1px solid #ccc;
//     border-radius: 4px;
//     padding: 10px;
//     box-sizing: border-box;
// }

.search-container {
    display: flex;
    margin-bottom: 15px;
}

.search-input {
    flex: 1;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px 0 0 4px;
    font-size: 14px;
}

.search-button {
    width: 40px;
    height: 36px;
    background-color: #f5f5f5;
    border: 1px solid #ddd;
    border-left: none;
    border-radius: 0 4px 4px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.icons-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    // gap: 10px 50px;
}

.icon-item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 40px;
}

.icon-text {
    font-size: 14px;
    color: #333;
    text-align: center;
    word-break: break-all;
}
</style>